<!DOCTYPE html>
<html>

<head><meta name="generator" content="Hexo 3.8.0">
  
  <title>vue 响应式系统基本原理 - 绪锋</title>
  <meta charset="UTF-8">
  <meta name="description" content="小镇青年,心怀远方">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  

    <!-- Site Verification -->
    <meta name="baidu-site-verification" content="cXpXJOvmtY">

  <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
  <meta name="description" content="Vue.js 是一款 MVVM 框架，数据模型仅仅是普通的 JavaScript 对象，但是对这些对象进行操作时，却能影响对应视图，它的核心实现就是「响应式系统」。">
<meta name="keywords" content="vue">
<meta property="og:type" content="article">
<meta property="og:title" content="vue 响应式系统基本原理">
<meta property="og:url" content="https://mraing.github.io/2019/12/15/vue-响应式系统基本原理/index.html">
<meta property="og:site_name" content="绪锋">
<meta property="og:description" content="Vue.js 是一款 MVVM 框架，数据模型仅仅是普通的 JavaScript 对象，但是对这些对象进行操作时，却能影响对应视图，它的核心实现就是「响应式系统」。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-12-16T01:55:39.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue 响应式系统基本原理">
<meta name="twitter:description" content="Vue.js 是一款 MVVM 框架，数据模型仅仅是普通的 JavaScript 对象，但是对这些对象进行操作时，却能影响对应视图，它的核心实现就是「响应式系统」。">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/mdui@0.4.3/dist/css/mdui.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.15.8/styles/atom-one-dark.css">
   
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">
  
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1038733_0xvrvpg9c0r.css">
  <link rel="stylesheet" href="/css/style.css?v=1627371788884">
</head>

<body class="mdui-drawer-body-left">
  
  <div id="nexmoe-background">
    <div class="nexmoe-bg" style="background-image: url(https://i.loli.net/2019/01/13/5c3aec85a4343.jpg)"></div>
    <div class="mdui-appbar mdui-shadow-0">
      <div class="mdui-toolbar">
        <a mdui-drawer="{target: '#drawer', swipe: true}" title="menu" class="mdui-btn mdui-btn-icon"><i class="mdui-icon material-icons">menu</i></a>
        <div class="mdui-toolbar-spacer"></div>
        <!--<a href="javascript:;" class="mdui-btn mdui-btn-icon"><i class="mdui-icon material-icons">search</i></a>-->
        <a href="/" title="LeeGeing" class="mdui-btn mdui-btn-icon"><img src="/images/avatar.jpg"></a>
       </div>
    </div>
  </div>
  <div id="nexmoe-header">
      <div class="nexmoe-drawer mdui-drawer" id="drawer">
    <div class="nexmoe-avatar mdui-ripple">
        <a href="/" title="LeeGeing">
            <img src="/images/avatar.jpg" alt="LeeGeing">
        </a>
    </div>
    <div class="nexmoe-count">
        <div><span>文章</span>82</div>
        <div><span>标签</span>28</div>
        <div><span>分类</span>8</div>
    </div>
    <ul class="nexmoe-list mdui-list" mdui-collapse="{accordion: true}">
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/" title="回到首页">
            <i class="mdui-list-item-icon nexmoefont icon-home"></i>
            <div class="mdui-list-item-content">
                回到首页
            </div>
        </a>
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/about.html" title="关于博客">
            <i class="mdui-list-item-icon nexmoefont icon-info-circle"></i>
            <div class="mdui-list-item-content">
                关于博客
            </div>
        </a>
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/PY.html" title="我的朋友">
            <i class="mdui-list-item-icon nexmoefont icon-unorderedlist"></i>
            <div class="mdui-list-item-content">
                我的朋友
            </div>
        </a>
        
    </ul>
    <aside id="nexmoe-sidebar">
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">社交按钮</h3>
    <div class="nexmoe-widget nexmoe-social">
        <a class="mdui-ripple" href="https://space.bilibili.com/11147795" target="_blank" mdui-tooltip="{content: '哔哩哔哩'}" style="color: rgb(231, 106, 141);background-color: rgba(231, 106, 141, .15);">
            <i class="nexmoefont icon-bilibili"></i>
        </a><a class="mdui-ripple" href="https://github.com/mraing/" target="_blank" mdui-tooltip="{content: 'GitHub'}" style="color: rgb(25, 23, 23);background-color: rgba(25, 23, 23, .15);">
            <i class="nexmoefont icon-github"></i>
        </a>
    </div>
</div>
  
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">文章分类</h3>
    <div class="nexmoe-widget">

      <ul class="category-list">

        


        

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/React/">React</a>
          <span class="category-list-count">7</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/TypeScript/">TypeScript</a>
          <span class="category-list-count">5</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/Vue/">Vue</a>
          <span class="category-list-count">33</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/前端/">前端</a>
          <span class="category-list-count">19</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/博客/">博客</a>
          <span class="category-list-count">3</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/工具/">工具</a>
          <span class="category-list-count">6</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/碎碎念/">碎碎念</a>
          <span class="category-list-count">4</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/软件设计师/">软件设计师</a>
          <span class="category-list-count">5</span>
        </li>

        
      </ul>

    </div>
  </div>


  
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">标签云</h3>
    <div id="randomtagcloud" class="nexmoe-widget tagcloud">
      <a href="/tags/Hbuilder/" style="font-size: 10px;">Hbuilder</a> <a href="/tags/Homebrew/" style="font-size: 10px;">Homebrew</a> <a href="/tags/JS/" style="font-size: 14px;">JS</a> <a href="/tags/JSX/" style="font-size: 10px;">JSX</a> <a href="/tags/Mint-UI/" style="font-size: 10px;">Mint-UI</a> <a href="/tags/Nginx/" style="font-size: 10px;">Nginx</a> <a href="/tags/Ngnix/" style="font-size: 10px;">Ngnix</a> <a href="/tags/OpenInTerminal/" style="font-size: 10px;">OpenInTerminal</a> <a href="/tags/Sass/" style="font-size: 14px;">Sass</a> <a href="/tags/Vuex/" style="font-size: 10px;">Vuex</a> <a href="/tags/antd/" style="font-size: 10px;">antd</a> <a href="/tags/css/" style="font-size: 10px;">css</a> <a href="/tags/docsify/" style="font-size: 10px;">docsify</a> <a href="/tags/git/" style="font-size: 12px;">git</a> <a href="/tags/hexo/" style="font-size: 12px;">hexo</a> <a href="/tags/mui/" style="font-size: 18px;">mui</a> <a href="/tags/react/" style="font-size: 14px;">react</a> <a href="/tags/redux/" style="font-size: 10px;">redux</a> <a href="/tags/swiper/" style="font-size: 10px;">swiper</a> <a href="/tags/typescript/" style="font-size: 16px;">typescript</a> <a href="/tags/vue/" style="font-size: 20px;">vue</a> <a href="/tags/vux/" style="font-size: 10px;">vux</a> <a href="/tags/她/" style="font-size: 10px;">她</a> <a href="/tags/感悟/" style="font-size: 12px;">感悟</a> <a href="/tags/日记/" style="font-size: 10px;">日记</a> <a href="/tags/消息推送/" style="font-size: 10px;">消息推送</a> <a href="/tags/知识点/" style="font-size: 10px;">知识点</a> <a href="/tags/软考笔记/" style="font-size: 16px;">软考笔记</a>
    </div>
    
  </div>

  
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">文章归档</h3>
    <div class="nexmoe-widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">七月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">三月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/10/">十月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/09/">九月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/07/">七月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/06/">六月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/04/">四月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/01/">一月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/12/">十二月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/09/">九月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/08/">八月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">七月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">六月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/05/">五月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/04/">四月 2019</a></li></ul>
    </div>
  </div>


  
</aside>
    <!-- <div class="nexmoe-copyright">
        &copy; 2021 LeeGeing
        Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
        & <a href="https://nexmoe.com/hexo-theme-nexmoe.html" target="_blank">Nexmoe</a>
    </div> -->
    <div class="nexmoe-copyright">
        <a href="http://beian.miit.gov.cn/state/outPortal/loginPortal.action" target="_blank">湘ICP备16019481号</a>
        <!-- & <a href="https://nexmoe.com/hexo-theme-nexmoe.html" target="_blank">Nexmoe</a> -->
    </div>
</div><!-- .nexmoe-drawer -->
  </div>
  <div id="nexmoe-content">
    <div class="nexmoe-primary">
        <div class="nexmoe-post">
    <div class="nexmoe-post-cover"> 
        
            <img src="https://i.loli.net/2019/01/13/5c3aec85a4343.jpg">
        
        <h1>vue 响应式系统基本原理</h1>
    </div>
  <div class="nexmoe-post-meta">
    <a><i class="nexmoefont icon-calendar-fill"></i>2019年12月15日</a>
    <a><i class="nexmoefont icon-areachart"></i>825 字</a>
    <a><i class="nexmoefont icon-time-circle-fill"></i>大概 3 分钟</a>
    
      <a class="nexmoefont icon-appstore-fill -link" href="/categories/Vue/">Vue</a>
    
    
      <a class="nexmoefont icon-tag-fill -link" href="/tags/vue/">vue</a>
    
  </div>
  <article>
    <blockquote>
<p>Vue.js 是一款 MVVM 框架，数据模型仅仅是普通的 JavaScript 对象，但是对这些对象进行操作时，却能影响对应视图，它的核心实现就是「响应式系统」。</p>
</blockquote>
<a id="more"></a>
<p>在 Vue 中，数据模型下的所有属性，会被 Vue 使用<code>Object.defineProperty</code>（Vue3.0 使用 Proxy）进行数据劫持代理。</p>
<p>响应式的核心机制是<strong>观察者模式</strong>，数据是被观察的一方，一旦发生变化，通知所有观察者，这样观察者可以做出响应，比如当观察者为视图时，视图可以做出视图的更新。</p>
<p>Vue.js 的响应式系统以来三个重要的概念，<code>Observer</code>、<code>Dep</code>、<code>Watcher</code>.</p>
<h3 id="Object-defineProperty"><a href="#Object-defineProperty" class="headerlink" title="Object.defineProperty()"></a>Object.defineProperty()</h3><p>我觉得先要从认识这个函数开始，何为<code>Object.defineProperty()</code> ? 这个方法它会直接在一个对象上定义一个新属性，或者修改一个对象的现有属性， 并返回这个对象。</p>
<p>它有三个参数</p>
<ul>
<li><p>obj: 要在其上定义的属性的对象，说白了就是你要操作对象</p>
</li>
<li><p>prop: 对象上的你需要修改的属性名称。</p>
</li>
<li><p>descriptor: 将被定义或修改的属性描述符。</p>
</li>
</ul>
<p>例子：</p>
<pre><code class="JavaScript">let obj = {}
obj.singer = &#39;周杰伦&#39;

// obj: 目标对象
// prop: 需要操作的目标对象的属性名
// descriptor: 描述符
Object.defineProperty(obj, &#39;music&#39;, {
  // value: &#39;刘德华&#39;,
  // writable : false,
  configurable: true,  // 可以配置对象，删除属性
  enumerable: true,     // 是否可以枚举
  // get,set设置时不能设置writable和value，它们代替了二者且是互斥的

  get () {
    return &#39;青花瓷&#39;
  },
  set (val) {
    console.log(&#39;视图更新&#39;);
  }
})
</code></pre>
<p>运行后，到浏览器的控制台中输入</p>
<pre><code class="JavaScript">obj
/* 打印
music: &quot;青花瓷&quot;
singer: &quot;周杰伦&quot;
get music: ƒ ()
set music: ƒ (val)
__proto__: Object
*/
</code></pre>
<p>当我们尝试更改数据,可以看到调用到了 set() 方法.</p>
<pre><code class="JavaScript">obj.music = &#39;稻香&#39;
/*
视图更新
&quot;稻香&quot;
*/
</code></pre>
<p>热身结束。我们开始下个阶段。</p>
<h3 id="响应式系统"><a href="#响应式系统" class="headerlink" title="响应式系统"></a>响应式系统</h3><blockquote>
<p>思路： -&gt; 获取数据 -&gt; 劫持数据 -&gt; 绑定监听方法</p>
</blockquote>
<pre><code class="JavaScript">// 调用它即代表更新视图
function cb(val) {
  console.log(&#39;视图更新了&#39;);
}

// 我们的 obj 的 key 属性在「读」的时候会触发 reactiveGetter 方法，
// 而在该属性被「写」的时候则会触发 reactiveSetter 方法。
function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    enumerable: true,       /* 属性可枚举 */
    configurable: true,     /* 属性可被修改或删除 */
    get: function reactiveGetter() {
      return val;         /* 实际上会依赖收集 */
    },
    set: function reactiveSetter(newVal) {
      if (newVal === val) {
        return
      };
      cb(newVal);
    }
  })
}
</code></pre>
<p><strong>Observe</strong> 扮演的角色是发布者，他的主要作用是在组件初始化的时，调用<code>defineReactive</code>函数，使用<code>Object.defineProperty</code>方法对对象的每一个子属性进行数据劫持/监听，即为每个属性添加<code>getter和setter</code>，将对应的属性值变成响应式。</p>
<pre><code class="JavaScript">/*
函数传入一个 value（需要「响应式」化的对象）,
通过遍历所有属性的方式对该对象的每一个属性都通过 defineReactive 处理。
*/
function observer(value) {
  // 当 val 为空的时候或者 val 不等于一个对象的时候，结束这次操作
  if (!value || typeof value !== &#39;object&#39;) {
    return
  }
  Object.keys(value).forEach((key) =&gt; {
    defineReactive(value, key, value[key]);
  })
}
</code></pre>
<pre><code class="JavaScript">&lt;!--模拟数据--&gt;
constructor(options) {
    this._data = options.data;
    observer(this._data);
}
</code></pre>
<p>最后在页面中调用</p>
<pre><code class="JavaScript">let o = new Vue({
  data: {
    name: &#39;Hello Word&#39;,
    age: &#39;18&#39;,
    hobby: &#39;PC Game&#39;
  }
})
</code></pre>

  </article>
  
    

  
  <section class="nexmoe-comment">
    <script id="dsq-count-scr" src="https://leegeing-cn.disqus.com/count.js" async></script>
<div id="disqus_thread"></div>
<script>
    var disqus_config = function () {
        this.page.url = 'https://mraing.github.io/2019/12/15/vue-响应式系统基本原理/'; // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = 'https://mraing.github.io/2019/12/15/vue-响应式系统基本原理/'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };
</script>
<script id="disqus-thread-script">
    (function() { // DON'T EDIT BELOW THIS LINE
        var d = document;
        var s = d.createElement('script');
        s.src = '//leegeing-cn.disqus.com/embed.js';
        s.setAttribute('data-timestamp', + new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>

</section>
</div>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/mdui@0.4.3/dist/js/mdui.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
 
    <script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>


 
    <script src="https://cdn.jsdelivr.net/npm/smoothscroll-for-websites@1.4.9/SmoothScroll.min.js"></script>


<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.15.8/build/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

<script src="/js/app.js?v=1627371788893"></script>
<script src="https://cdn.jsdelivr.net/npm/lazysizes@5.1.0/lazysizes.min.js"></script>


    <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/xtaodada/xtaodada.github.io@0.0.2/copy.js"></script>

  





</body>

</html>
